package turtle.system.pt;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import arbor.mining.util.date.DateUtil;

/**
 * 取出一段時間,觀查其獲利
 * 結果放在data/evaluate.txt
 * tmp/consHist.csv:保守法每區間獲利列表
 * tmp/posiHist.csv:積極法每區間獲利列表
 * tmp/integHist.csv
 * tmp/mddConsHist.csv:保守法每區間最低獲利列表
 * tmp/mddPosiHist.csv:積極法每區間最低獲利列表
 * @author ktchuang
 * 
 */
public class YearEvaluator {

	public static String initialDate = "1999/01/05";
	public static String endDate = "2009/03/07";
	public static int numYears = 3;
	public static int monthStep = 1;
	public static GregorianCalendar startCal, endCal;
	static Date leastDay = null;
	public static final String WTX0_YEARS_FN = "tmp/1000-partial.txt";
	public static final String WTX1_YEARS_FN = "tmp/WTX1-partial.txt";
	private Date startTime, endTime;

	ArrayList<MDD> consMddList = new ArrayList<MDD>();
	ArrayList<MDD> posiMddList = new ArrayList<MDD>();
	StatCalc posiAccPro = new StatCalc();
	StatCalc consAccPro = new StatCalc();
	StatCalc integAccPro = new StatCalc();

	public void beginProc(Date startTime, Date endTime) {
		this.startTime = startTime;
		this.endTime = endTime;

		getPartialData();

		try {
			exec();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private boolean isBetween(Date day) {
		return (!day.before(startTime) && !day.after(endTime));
	}

	private void getPartialData() {
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		try {
			BufferedReader reader = null;
			BufferedWriter writer = null;
			String line;
			reader = new BufferedReader(new FileReader(DailyExec.WTX1_PREFIX_FN
					+ DailyExec.FN_SUFFIX));
			reader.readLine();
			reader.readLine();
			reader.readLine();
			writer = new BufferedWriter(new FileWriter(WTX1_YEARS_FN));
			writer.write(DailyExec.WTX1_WORD);
			while ((line = reader.readLine()) != null) {
				String d = line.split(" 	")[0];
				if (isBetween(df.parse(d))) {
					writer.write(line + "\n");
				}
			}
			reader.close();
			writer.flush();
			writer.close();

			reader = new BufferedReader(new FileReader(DailyExec.WTX0_PREFIX_FN
					+ DailyExec.FN_SUFFIX));
			reader.readLine();
			reader.readLine();
			reader.readLine();
			writer = new BufferedWriter(new FileWriter(WTX0_YEARS_FN));
			writer.write(DailyExec.WTX0_WORD);
			while ((line = reader.readLine()) != null) {
				String d = line.split(" 	")[0];
				if (isBetween(df.parse(d))) {
					writer.write(line + "\n");
				}
			}
			reader.close();
			writer.flush();
			writer.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	static BufferedWriter writer = null;

	public void exec() throws IOException {
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		PriceDataStopProfit cons = new PriceDataStopProfit(PriceData.STRATEGY_CONSERVATIVE,
				WTX0_YEARS_FN, WTX1_YEARS_FN);
		ArrayList<Double> consProfitValues = null;
		ArrayList<Double> posiProfitValues = null;
		String consSum = cons.getSummary();
		String conservative = cons.getFinalSuggestion();
		double cons_acc = cons.getAcc();
		consAccPro.enter(cons_acc);
		consMddList.add(cons.getMDD());
		// PriceData.copyFile("data/stock.log",
		// "tmp/cons-"+df.format(this.startTime)+"-"+df.format(this.endTime)+".txt");
		consProfitValues = cons.getProfitStat().valueList;
		PriceDataStopProfit posi = new PriceDataStopProfit(PriceData.STRATEGY_POSITIVE,
				WTX0_YEARS_FN, WTX1_YEARS_FN);

		String postSum = posi.getSummary();
		String positive = posi.getFinalSuggestion();
		double post_acc = posi.getAcc();
		posiProfitValues = posi.getProfitStat().valueList;
		posiAccPro.enter(post_acc);
		posiMddList.add(posi.getMDD());
		integAccPro.enter(cons_acc + post_acc);
		// PriceData.copyFile("data/stock.log",
		// "posi-"+df.format(this.startTime)+"-"+df.format(this.endTime)+".txt");

		System.out.println("=================================");
		System.out.println("保守建議:\n" + conservative);
		System.out.println("保守策略Summary:\n" + consSum);
		System.out.println("積極建議:\n" + positive);
		System.out.println("積極策略Summary:\n" + postSum);
		try {
			// writer.write(cons_acc+"\n");
			// writer.write(post_acc+"\n");
			writer.write("保守策略Summary:\n" + consSum + "\n");
			writer.write("保守策略MDD:\n");
			writer.write(cons.getMDD().toString());
			writer.write("---------------------------------\n");
			writer.write("積極策略Summary:\n" + postSum + "\n");
			writer.write("積極策略MDD:\n");
			writer.write(posi.getMDD().toString());
			writer.write("=================================\n");
		} catch (IOException e) {
			System.out.println(e);
		}

		try {
			BufferedWriter writer1 = new BufferedWriter(new FileWriter(
					DailyExec.CONS_PROFIT_HISTOGRAM_FN));
			BufferedWriter writer2 = new BufferedWriter(new FileWriter(
					DailyExec.POSI_PROFIT_HISTOGRAM_FN));
			for (int i = 0; i < consProfitValues.size(); i++) {
				writer1.write(consProfitValues.get(i) + "\n");
			}
			for (int i = 0; i < posiProfitValues.size(); i++) {
				writer2.write(posiProfitValues.get(i) + "\n");
			}
			writer1.close();
			writer2.close();
		} catch (IOException e) {
			System.out.println(e);
		}
	}

	public YearEvaluator() {
		try {
			writer = new BufferedWriter(new FileWriter("data/evaluate.txt"));
		} catch (IOException e) {
			System.out.println(e);
		}

		startCal = new GregorianCalendar();
		endCal = new GregorianCalendar();

		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		Date s = null;
		try {
			s = df.parse(initialDate);
			leastDay = df.parse(endDate);

			startCal.setTime(s);
			endCal.setTime(s);
			endCal.add(Calendar.YEAR, numYears);
		} catch (Exception e) {
			;
		}
		while (!leastDay.before(endCal.getTime())) {
			try {
				writer.write(df.format(startCal.getTime()) + "-"
						+ df.format(endCal.getTime()) + "\n");

			} catch (IOException e) {
				System.out.println(e);
			}
			this.beginProc(startCal.getTime(), endCal.getTime());
			startCal.add(Calendar.MONTH, monthStep);
			endCal.add(Calendar.MONTH, monthStep);
		}

		try {
			writer.write("保守策略統計結果:\n");
			writer.write("共" + consAccPro.getCount() + "統計\n");
			writer.write("Max:" + consAccPro.getMax() + "\n");
			writer.write("Min:" + consAccPro.getMin() + "\n");
			writer.write("Dev:" + consAccPro.getStandardDeviation() + "\n");
			writer.write("負值次數:" + consAccPro.getNegativeCount() + "\n");
			writer.write("正值次數:" + consAccPro.getPositiveCount() + "\n");
			writer.write("面臨損失時平均虧損:" + (int) consAccPro.getNegativeMean()
					+ "\n");
			writer.write("平均點數：" + consAccPro.getSum()
					/ (double) consAccPro.getCount() + "\n");
			writer.write("積極策略統計結果:\n");
			writer.write("共" + posiAccPro.getCount() + "統計\n");
			writer.write("Max:" + posiAccPro.getMax() + "\n");
			writer.write("Min:" + posiAccPro.getMin() + "\n");
			writer.write("Dev:" + posiAccPro.getStandardDeviation() + "\n");
			writer.write("負值次數:" + posiAccPro.getNegativeCount() + "\n");
			writer.write("正值次數:" + posiAccPro.getPositiveCount() + "\n");
			writer.write("面臨損失時平均虧損:" + (int) posiAccPro.getNegativeMean()
					+ "\n");
			writer.write("平均點數：" + posiAccPro.getSum()
					/ (double) posiAccPro.getCount() + "\n");

			writer.close();

		} catch (IOException e) {
			System.out.println(e);
		}

		try {
			BufferedWriter consWriter = new BufferedWriter(new FileWriter(
					"tmp/consHist.csv"));
			BufferedWriter posiWriter = new BufferedWriter(new FileWriter(
					"tmp/posiHist.csv"));
			BufferedWriter integWriter = new BufferedWriter(new FileWriter(
					"tmp/integHist.csv"));
			BufferedWriter mddConsWriter = new BufferedWriter(new FileWriter(
					"tmp/mddConsHist.csv"));
			BufferedWriter mddPosiWriter = new BufferedWriter(new FileWriter(
					"tmp/mddPosiHist.csv"));
			ArrayList<Double> values = consAccPro.valueList;
			for (int i = 0; i < values.size(); i++) {
				consWriter.write(values.get(i) + "\n");
			}
			values = posiAccPro.valueList;
			for (int i = 0; i < values.size(); i++) {
				posiWriter.write(values.get(i) + "\n");
			}
			values = integAccPro.valueList;
			for (int i = 0; i < values.size(); i++) {
				integWriter.write(values.get(i) + "\n");
			}

			for (int i = 0; i < consMddList.size(); i++)
				mddConsWriter.write(consMddList.get(i).getMaxDrawDown() + "\n");

			for (int i = 0; i < posiMddList.size(); i++)
				mddPosiWriter.write(posiMddList.get(i).getMaxDrawDown() + "\n");

			consWriter.close();
			posiWriter.close();
			integWriter.close();
			mddPosiWriter.close();
			mddConsWriter.close();
		} catch (IOException e) {
			System.out.println(e);
		}

	}

	public static void main(String[] args) {
        new YearEvaluator();
	}

}
